package com.jfinal.weixin.demo;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.HashKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.weixin.sdk.api.*;
import com.jfinal.weixin.sdk.cache.IAccessTokenCache;
import com.jfinal.weixin.sdk.jfinal.ApiController;

import javax.servlet.ServletInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.Calendar;

public class WeixinApiController extends ApiController {

    static IAccessTokenCache accessTokenCache = ApiConfigKit.getAccessTokenCache();

    public void getToken() {
        String key = getPara("key");
        String json = accessTokenCache.get(key);
        renderText(json);
    }

    /**
     * 获取公众号菜单
     */
    public void getMenu() {
        ApiResult apiResult = MenuApi.getMenu();
        if (apiResult.isSucceed())
            renderText(apiResult.getJson());
        else
            renderText(apiResult.getErrorMsg());
    }

    /**
     * 创建菜单
     */
    public void createMenu() {
        String str = "{\n" +
                "    \"button\": [\n" +
                "        {\n" +
                "            \"name\": \"进入理财\",\n" +
                "            \"url\": \"http://m.bajie8.com/bajie/enter\",\n" +
                "            \"type\": \"view\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"name\": \"安全保障\",\n" +
                "            \"key\": \"112\",\n" +
                "\t    \"type\": \"click\"\n" +
                "        },\n" +
                "        {\n" +
                "\t    \"name\": \"使用帮助\",\n" +
                "\t    \"url\": \"http://m.bajie8.com/footer/cjwt\",\n" +
                "\t    \"type\": \"view\"\n" +
                "        }\n" +
                "    ]\n" +
                "}";
        ApiResult apiResult = MenuApi.createMenu(str);
        if (apiResult.isSucceed())
            renderText(apiResult.getJson());
        else
            renderText(apiResult.getErrorMsg());
    }

    /**
     * 获取公众号关注用户
     */
    public void getFollowers() {
        ApiResult apiResult = UserApi.getFollows();
        renderText(apiResult.getJson());
    }

    /**
     * 获取用户信息
     */
    public void getUserInfo() {
        ApiResult apiResult = UserApi.getUserInfo("oWsOQuB6HZeJ0_Op5eohHJv11qkE");
        renderText(apiResult.getJson());
    }

    /**
     * 发送模板消息
     */
    public void sendMsg() {
        String content = this.getPara("content");
        String str = " {\n" +
                "           \"touser\":\"oWsOQuB6HZeJ0_Op5eohHJv11qkE\",\n" +
                "           \"template_id\":\"MITlq4ER6CMqf0a0w28n7ghvDhx7oUUMSLBVOXvdpP8\",\n" +
                "           \"topcolor\":\"#FF0000\",\n" +
                "           \"data\":{\n" +
                "                   \"REMARK\": {\n" +
                "                       \"value\":\"" + content + "\"\n" +
                "                   }\n" +
                "           }\n" +
                "       }";
        ApiResult apiResult = TemplateMsgApi.send(str);
        renderText(apiResult.getJson());
    }

    /**
     * 获取参数二维码
     */
    public void getQrcode() {
        String str = "{\"expire_seconds\": 604800, \"action_name\": \"QR_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": 123}}}";
        ApiResult apiResult = QrcodeApi.create(str);
        renderText(apiResult.getJson());

//        String str = "{\"action_name\": \"QR_LIMIT_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \"123\"}}}";
//        ApiResult apiResult = QrcodeApi.create(str);
//        renderText(apiResult.getJson());
    }

    /**
     * 长链接转成短链接
     */
    public void getShorturl() {
        String str = "{\"action\":\"long2short\"," +
                "\"long_url\":\"http://wap.koudaitong.com/v2/showcase/goods?alias=128wi9shh&spm=h56083&redirect_count=1\"}";
        ApiResult apiResult = ShorturlApi.getShorturl(str);
        renderText(apiResult.getJson());
    }

    /**
     * 获取客服聊天记录
     */
    public void getRecord() {
        String str = "{\n" +
                "    \"endtime\" : 987654321,\n" +
                "    \"pageindex\" : 1,\n" +
                "    \"pagesize\" : 10,\n" +
                "    \"starttime\" : 123456789\n" +
                " }";
        ApiResult apiResult = CustomServiceApi.getRecord(str);
        renderText(apiResult.getJson());
    }

    /**
     * 获取微信服务器IP地址
     */
    public void getCallbackIp() {
        ApiResult apiResult = CallbackIpApi.getCallbackIp();
        renderText(apiResult.getJson());
    }

    public void saveNickNames() throws IOException {
        getRequest().setCharacterEncoding("utf-8");
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream) getRequest().getInputStream(), "utf-8"));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            JSONObject obj = JSONObject.parseObject(sb.toString());
            JSONArray arr = obj.getJSONArray("nickNames");
            String uin = obj.getString("uin");
            if (null != arr && arr.size() > 0) {
                JSONObject arrObj = null;
                String name = "";
                int counts = 0;
                int mcount = 0;
                String tag = "";
                for (int i = 0; i < arr.size(); i++) {
                    arrObj = arr.getJSONObject(i);
                    name = arrObj.getString("nickName");
                    mcount = arrObj.getInteger("count");
                    tag = HashKit.md5(name);
                    counts = 0;
                    try {
                        counts = Db.queryInt(" select counts from invite_counts where tag = ? ", new Object[]{
                                tag
                        });
                    }catch (Exception e1){

                    }
                    if (counts > 0) {
                        counts = counts + mcount;
                        Db.update(" update invite_counts set counts = ? where wxid = ? and tag = ? ", new Object[]{
                                counts, uin, tag
                        });
                    } else {
                        counts = counts + mcount;
                        Db.update(" insert into invite_counts (tag,wxid,counts,nick_name) values (?,?,?,?)", new Object[]{
                                tag, uin, counts, name
                        });
                    }
                }
            }
            renderText("ok", "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
            renderText("fail", "utf-8");
        }
    }

    public void auth() {
        String url = SnsAccessTokenApi.getAuthorizeURL(ApiConfigKit.getAppId(), "http://wxtest.lily0.com/api/authr", false);
        redirect(url);
    }

    public void authr() throws Exception {
        String code = getPara("code");
        SnsAccessToken sat = SnsAccessTokenApi.getSnsAccessToken(ApiConfigKit.getAppId(), ApiConfigKit.getApiConfig().getAppSecret(), code);
        String openId = sat.getOpenid();
        //判断下是否是会员，如果是，直接跳转
        long memberCounts = Db.queryLong(" select count(*) as c from mac_user where u_openid = ? ", new Object[]{
                openId
        });
        //如果不是会员
        if (memberCounts <= 0L) {
            ApiResult apiResult = SnsApi.getUserInfo(sat.getAccessToken(), sat.getOpenid());
            JSONObject jsonObject = JSONObject.parseObject(apiResult.getJson());
            String tag = jsonObject.getString("nickname");
            tag = HashKit.md5(tag);
            int counts = 0;
            try {
                counts = Db.queryInt(" select counts from invite_counts where tag = ? ", new Object[]{
                        tag
                });
            } catch (Exception e1) {

            }
            //如果大于5个，可以认证为会员
            if (counts >= 5) {
                int vipGroup = 2;
                String sql = " insert into mac_user ";
                sql += " (u_qid,u_name,u_password,u_qq,u_email,u_phone,u_status,u_flag,u_question,u_answer,u_group,u_points,u_regtime,u_logintime,u_loginnum,u_extend,u_loginip,u_random,u_fav,u_plays,u_downs,u_start,u_end,u_openid) ";
                sql += " values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ";
                Long time = Calendar.getInstance().getTime().getTime();
                Db.update(sql, new Object[]{
                        "", openId, HashKit.md5(openId), "", "", "", 1, 0, "", "", 2, 1, time.intValue(), time.intValue(),
                        0, 0, 0, "", "", ",102-1-1,", "", 0, 0, openId
                });
            } else {
                renderText("您还不是VIP会员，请您邀请至少5个人进群后，方可升级成VIP！");
                return;
            }
        }
        String param = ThreeDES.encode(openId);
        param = param.replaceAll("-", "+").replaceAll("_", "/").replaceAll(" ", "");
        param = URLEncoder.encode(param, "utf-8");
        String signature = openId + "|www.showplus.cn";
        signature = HashKit.md5(signature);
        signature = HashKit.md5(signature);
        redirect("http://motest.lily0.com/index.php?m=user-cmcheck.html&param=" + param + "&signature=" + signature);
    }

}

